﻿using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using log4net;
using log4net.Appender;
using log4net.Core;

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
namespace Log.Common.Log4Net
{
   public class Log4NetLog:ILog
   {

       private log4net.ILog _log = null;

       public Log4NetLog()
       {
           _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
       }

       public void Info(string message, bool isWriteCaller = false, [CallerMemberName] string memberName = "",
           [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
       {
           if (isWriteCaller)
           {
               _log.Info($"{sourceFilePath}\r\n{memberName}  {sourceLineNumber}\r\n{message}");
           }
           else
           {
               _log.Info(message);
           }
       }

       public void Error(Exception ex, bool isWriteCaller = true, [CallerMemberName] string memberName = "",
           [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
       {
           if (isWriteCaller)
           {
               _log.Error($"{sourceFilePath}\r\n{memberName}  {sourceLineNumber}\r\n{ex}");
           }
           else
           {
               _log.Error(ex);
           }
       }

       public void Error(string message, Exception ex, bool isWriteCaller = true,
           [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "",
           [CallerLineNumber] int sourceLineNumber = 0)
       {
           if (isWriteCaller)
           {
               _log.Error($"{sourceFilePath}\r\n{memberName}  {sourceLineNumber}\r\n{message}\r\n{ex}");
           }
           else
           {
               _log.Error($"{message}\r\n{ex}");
           }
       }

       public void Configure(string dir)
        {
            var repositorys = LoggerManager.GetAllRepositories();
            foreach (var repository in repositorys)
            {
                // var repository = LogManager.GetRepository(_repository.Name);
                var appenders = repository.GetAppenders();
                if (appenders.FirstOrDefault() is RollingFileAppender targetApder)
                {
                    targetApder.File = dir+"\\";
                    targetApder.ActivateOptions();
                }
            }
        }
   }
}
